//
//  HomeViewController.m
//  CI
//
//  Created by tongbu_jinzhongjun on 14-10-21.
//  Copyright (c) 2014年 tongbu_jinzhongjun. All rights reserved.
//

#import "HomeViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "Hospital.h"
#import "Type.h"
#import "Company.h"
#import "Product.h"
#import "UserProduct.h"
#import "CompanyProduct.h"
#import <CoreData+MagicalRecord.h>
@interface HomeViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString *filePath =[resourcePath stringByAppendingPathComponent:@"index.html"];
    NSString*htmlstring=[[NSString alloc] initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil];
    
    [self.webView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
    self.webView.scrollView.contentSize = CGSizeZero;

//    NSString *js_string = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"index.js" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
//    [self.webView stringByEvaluatingJavaScriptFromString:js_string];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    [self js_call_objectiveC];
    
    return YES;
}


-(void) webViewDidFinishLoad:(UIWebView *)webView{
    [self js_call_objectiveC];
}

-(void) js_call_objectiveC {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    
    context[@"getHospital"] = ^{
        
        NSArray *array = [Hospital MR_findAll];
        NSMutableArray *mutableArray = [NSMutableArray array];
        for (Hospital *hospital in array) {
            [mutableArray addObject:[hospital toJson]];
        }
        NSData *data = [NSJSONSerialization dataWithJSONObject:mutableArray options:NSJSONWritingPrettyPrinted error:nil];
        
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    };
    context[@"getType"] = ^{
        NSArray *array = [Type MR_findAll];
        NSMutableArray *mutableArray = [NSMutableArray array];
        for (Type *type in array) {
            [mutableArray addObject:[type toJson]];
        }
        NSData *data = [NSJSONSerialization dataWithJSONObject:mutableArray options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    };
    context[@"getCompany"] = ^{
        NSArray *array = [Company MR_findAll];
        NSMutableArray *mutableArray = [NSMutableArray array];
        for (Company *company in array) {
            [mutableArray addObject:[company toJson]];
        }
        NSData *data = [NSJSONSerialization dataWithJSONObject:mutableArray options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    };
    
    context[@"getProduct"] = ^ {
        NSArray *array = [Company MR_findAll];
        NSMutableArray *company_mutableArray = [NSMutableArray array];
        for (Company *company in array) {
            NSMutableDictionary *company_dictionary = [NSMutableDictionary dictionary];
            NSNumber* company_id = company.company_id;
            NSString* company_name = company.company_name;
            //根据company_id找到所有的产品
            NSArray *product_array = [Product MR_findByAttribute:@"company_id" withValue:company_id];
            NSMutableArray *product_mutableArray = [NSMutableArray array];
            for (Product *product in product_array) {
                NSDictionary *product_dictionary = [NSDictionary dictionaryWithObjectsAndKeys:product.product_name,@"name",product.product_id,@"productId",product.count,@"count", nil];
                [product_mutableArray addObject:product_dictionary];
            }
            
            [company_dictionary setObject:company_id forKey:@"companyId"];
            [company_dictionary setObject:company_name forKey:@"name"];
            [company_dictionary setObject:product_mutableArray forKey:@"product"];
            
            [company_mutableArray addObject:company_dictionary];
        }
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:company_mutableArray options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
    };
    
   /* context[@"getProduct"] = ^(NSString *hospitalId,NSString *typeId,NSString *companyId,NSString*productId,NSString*count) {
        NSArray *array = [UserProduct MR_findAllSortedBy:@"user_product_id" ascending:YES withPredicate:[NSPredicate predicateWithFormat:@"hospital_id == %@ AND type_id == %@ AND company_id == %@ && ",hospitalId,typeId,companyId]];
        NSMutableArray *mutableArray = [NSMutableArray array];
        for (UserProduct *pro in array) {
            Product *product = [[Product MR_findByAttribute:@"product_id" withValue:pro.product_id] objectAtIndex:0];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:pro.product_id,@"productId",pro.count,@"count",product.product_name,@"name", nil];
            [mutableArray addObject:dic];
        }
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:mutableArray options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    };*/
    
    context[@"getUserId"] = ^{
        return [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    };
    
    context[@"getUerProduct"] = ^(NSString *hospitalId,NSString *typeId,NSString *companyId,NSString*productId,NSString*count) {

        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"productId",@" ATS STD",@"name",@"10",@"count", nil];
        NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"productId",@" ATS AP",@"name",@"12",@"count",nil];
       
        NSArray *arr = [NSArray arrayWithObjects:dic,dic2, nil];
        NSData *da = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:da encoding:NSUTF8StringEncoding];

    };
    
    context[@"saveProductInfo"] = ^(NSString *hospitalId,NSString* typeId,NSString* companyId,NSString* productId,NSString* count){
        
        //有网络的情况下上传数据
        if([AFNetworkReachabilityManager sharedManager].reachable) {
            [self postProductInfoWithHospitalId:hospitalId typeId:typeId companyId:companyId productId:productId count:count];
        }
        //没有网络的情况下，保存数据，在有网络的情况，或者下次登陆时上传数据
        [self saveWithProductId:productId typeId:typeId companyId:companyId hospitalId:hospitalId count:count];
        
    };
}

-(void) postProductInfoWithHospitalId:(NSString*) hospitalId typeId:(NSString*)typeId
                            companyId:(NSString*) companyId productId:(NSString*)productID
                                count:(NSString*) count {
    NetWorkRequest *request = [[JSObjection defaultInjector] getObject:[NetWorkRequest class]];
    [request postProductInfoWithHospitalId:hospitalId typeId:typeId companyId:companyId productId:productID count:count];
}

-(void) saveWithProductId:(NSString*)productId typeId:(NSString*)typeId companyId:(NSString*)companyId
               hospitalId:(NSString*)hospitalId count:(NSString*)count {
    NSArray *array = [UserProduct MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"company_id == %@ AND product_id == %d",companyId,productId]];
    
    UserProduct *product = nil;
    if ([array count] > 0) {
        product = [array objectAtIndex:0];
    }else {
        product = [UserProduct MR_createEntity];
    }
    
    product.product_id = [NSNumber numberWithInt:productId.intValue];
    product.type_id = [NSNumber numberWithInt:typeId.intValue];
    product.company_id = [NSNumber numberWithInt:companyId.intValue];
    product.hospital_id = [NSNumber numberWithInt:hospitalId.intValue];
    product.count = [NSNumber numberWithInt:count.intValue];
    product.state = @1;
    
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        
    }];
    //存到product表中
    NSArray *array_product = [Product MR_findAllWithPredicate:[NSPredicate predicateWithFormat:@"company_id == %@ AND product_id == %@",companyId,productId]];
    
    Product *product_ = nil;
    if ([array_product count] > 0) {
        product_ = [array_product objectAtIndex:0];
    }else {
        product_ = [Product MR_createEntity];
    }
    product_.product_id = [NSNumber numberWithInt:productId.intValue];
    product_.company_id = [NSNumber numberWithInt:companyId.intValue];
    product_.count = [NSNumber numberWithInt:count.intValue];

    
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
